<template>
  <basic-container>
    <div class="page-wrap">
      <div class="container buyer-info">
        <h4 class="title">基本信息</h4>
        <el-form ref="customerForm"
                 :rules="customerRules"
                 :model="customerOrder"
                 size="small"
                 :inline="true"
                 label-width="100px">
          <el-form-item label="手机:" prop="telephone">
            <el-select class="form-field" filterable
                       v-model="customerOrder.telephone"
                       remote
                       :remote-method="remoteTelephone"
                       placeholder="请选择"
                       @change="onBuyerChange($event, 'telephone')">
              <el-option
                v-for="item in buyerList"
                :key="item.telephone"
                :label="item.telephone"
                :value="item.telephone">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="联系人:">
            <el-select
              class="form-field"
              filterable v-model="customerOrder.contact"
              remote
              :remote-method="remoteContact"
              placeholder="请选择"
              @change="onBuyerChange($event, 'contact')">
              <el-option
                v-for="item in buyerList"
                :key="item.contact"
                :label="item.contact"
                :value="item.contact">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="采购商名称:">
            <el-select
              class="form-field" filterable
              v-model="customerOrder.buyerName"
              remote
              :remote-method="remoteBuyerName"
              placeholder="请选择"
              @change="onBuyerChange($event, 'buyerName')">
              <el-option
                v-for="item in buyerList"
                :key="item.buyerName"
                :label="item.buyerName"
                :value="item.buyerName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="配送时间:" prop="deliveryTime">
            <el-date-picker
              :editable="false"
              class="form-field"
              v-model="customerOrder.deliveryTime"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              @change="changeTime">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="配送时段:" prop="buySeq">
            <el-select
              class="form-field"
              v-model="customerOrder.buySeq"
              placeholder="请选择"
              @change="changebuySeq">
              <el-option
                v-for="item in buySeqs"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="配送方式:" prop="deliveryType">
            <el-select class="form-field"
                       v-model="customerOrder.deliveryType"
                       placeholder="请选择">
              <el-option
                v-for="item in deliveryTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注:" prop="needNote">
            <el-input
              class="form-field"
              v-model="customerOrder.needNote"
              placeholder="">
            </el-input>
          </el-form-item>
          <el-form-item label=" ">
            <el-button type="primary" @click="resetForm">重置</el-button>
            <el-button type="primary" @click="showTextArea">录入</el-button>
            <el-button type="primary" size="small" :disabled="disabled" @click="is_excel = true">导入商品明细</el-button>
            <div v-if="is_excel">
              <el-dialog title="导入Excel" :visible.sync="is_excel" class="is_excel" width="80%"
                         :before-close="handleClose">
                <excel_box ref="excelBox" down="1" :data="listData" @select="onSelectList"></excel_box>
              </el-dialog>
            </div>
          </el-form-item>
          <el-form-item label="平台店铺：">
            <el-select v-model="shopId">
              <el-option v-for="(item,index) in shopList"
                      :key="index"
                      :label="item.name"
                      :value="item.shopId"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-top:10px" v-show="orderTextVisible">
        <el-input type="textarea" v-model="orderText" cols="40" rows="4"></el-input>
        <el-button @click="orderText=''">清 空</el-button>
        <el-button @click="orderTextSubmit">提 交</el-button>
        <el-button @click="orderSort">排 序</el-button>
      </div>

      <div class="container body">
        <h4 class="title">采购列表</h4>
        <el-table class="goods-list" max-height="550" :data="orderList" border :header-cell-style="thStyle">
          <el-table-column
            width="50">
            <template slot-scope="scope">
              <div style="text-align: center">{{scope.$index + 1}}</div>
            </template>
          </el-table-column>
          <el-table-column
            type="index"
            width="100">
            <template slot-scope="scope">
              <img style="display:block;width:50px;height:50px;"
                   :src="scope.row.modelUrl + `?x-oss-process=image/resize,w_200`"
                   alt="" v-show="scope.row.modelUrl">
            </template>
          </el-table-column>
          <el-table-column prop="buyerName">
            <template slot-scope="scope">
              <el-form
                :ref="'orderDetail' + scope.$index"
                :rules="orderDetailRules"
                :inline="true"
                :model="scope.row"
                size="small"
                class="demo-form-inline"
                label-width="60px">
                <el-row class="row">
                  <el-form-item
                    label="商品名称:"
                    prop="goodsName"
                    label-width="85px">
                    <el-select
                      clearable
                      filterable
                      default-first-option
                      :disabled="disabled"
                      v-model="scope.row.goodsName"
                      remote :remote-method="searchGoodsByName(scope.row)"
                      :loading="scope.row.loading"
                      @change="onGoodsSelectChange($event, scope.row)"
                      placeholder="输入名称查询" style="width: 550px;">
                      <el-option
                        v-for="item in scope.row.goodsList"
                        :key="item.modelId" :label="item.goodsName + '(' + item.modelName+')'"
                        :value="item.modelId">
                      </el-option>
                    </el-select>
                    <el-button type="text"
                               :disabled="disabled"
                               @click="showGoodsDialog($event, scope.$index)"
                    >所有商品
                    </el-button>
                  </el-form-item>
<!--                  <el-form-item label="规格:" prop="goodsId">-->
<!--                    <el-select-->
<!--                      v-model="scope.row.goodsId"-->
<!--                      @change="onModelSelectChange($event, scope.row)"-->
<!--                      placeholder="请选择" style="width: 200px;">-->
<!--                      <el-option-->
<!--                        v-for="item in scope.row.goodsModelList"-->
<!--                        :key="item.id"-->
<!--                        :label="item.modelName+' /单位:'+item.modelUnit"-->
<!--                        :value="item.id">-->
<!--                      </el-option>-->
<!--                    </el-select>-->
<!--                  </el-form-item>-->
                  <el-form-item v-show="scope.row.purchasePrice" label="市场价:">
                    {{scope.row.purchasePrice}}元 / {{scope.row.modelUnit}}
                  </el-form-item>
                  <el-form-item label="采购价:" prop="buyPrice">
                    <el-input
                      class="form-field--small"
                      v-model="scope.row.buyPrice"
                      maxlength="10"
                      placeholder="采购价">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="数量:" prop="goodsNum">
                    <el-input
                      class="form-field--small"
                      v-model="scope.row.goodsNum"
                      maxlength="10"
                      placeholder="采购数量">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="备注:" prop="remarks">
                    <el-input
                      class="form-field--small"
                      v-model="scope.row.remarks"
                      placeholder="备注">
                    </el-input>
                  </el-form-item>
                </el-row>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column width="120" align="center">
            <template slot-scope="scope">
              <el-button
                type="danger" plain
                icon="el-icon-delete"
                @click="delOrderItem(scope.row, scope.$index)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
<!--        <div v-if="dialogVisible">-->
<!--          <el-dialog title="选择商品" :visible.sync="dialogVisible">-->
<!--            <goods-list @select="onSelectGoods" :buyer-id="customerOrder.buyerId"-->
<!--                        :delivery-date="customerOrder.deliveryTime"></goods-list>-->
<!--          </el-dialog>-->
<!--        </div>-->
        <div style="margin-top: 10px;">
          <el-button
            type="primary" plain
            @click="addOrderItem"
            icon="el-icon-plus">增加
          </el-button>
          <el-button
            type="primary"
            @click="submitBuyOrder">提交订单
          </el-button>
        </div>
      </div>
    </div>
    <el-dialog
      title="平台商品列表"
      :visible.sync="dialogVisible"
      width="90%"
      :before-close="handleClose"
    >
      <supply-bind @selectGoods="selectGoods"
      ></supply-bind>
    </el-dialog>
  </basic-container>
</template>

<script>
  import supplyBind from "./components/supplyBind";
  import Request from './../request.js';
  import rules from './rules.js';
  import goodsList from './components/goodsList.vue';
  import {
    queryStatus
  } from "@/api/saleb/queryStatus"
  import {getStore, setStore} from "@/util/store";
  import Excel_box from "@/components/pds/common/excel_box";
  import {
    importTable
  } from '@/api/saleb/importTable';
  import {addNewOder} from "../../../api/saleb/buyorder"
  import {getBuyerList} from '../../../api/saleb/buyer'
  import {getgoodslist} from '../../../api/supply/supply_goods_info'
  import {fetchList} from "../../../api/manage/shop";
  function data() {
    return {
      request: new Request(),
      customerRules: rules.customerRules,
      orderDetailRules: rules.orderDetailRules,
      disabled: true,
      customerOrder: this.customerOrderInfo(),
      orderList: this.orderListInfo(),
      selectedRowIndex: '',
      buyerList: [],
      // 选择标签
      buySeqs: this.$dic.buySeqOptions,
      deliveryTypeOptions: this.$dic.deliveryTypeOptions,
      dialogVisible: false,
      printDialogVisible: false,
      printTitle: {},
      printTable: [],
      orderInfo: {},
      // 文本域
      orderText: '',
      orderTextVisible: false,
      is_excel: false,
      listData: {},
      shopId: '',
      shopList: [],
      pmId: ''
    };
  }

  export default {
    data: data,
    computed: {},
    components: {
      goodsList, Excel_box,supplyBind
    },
    mounted() {
      this.fetchBuyerList()
      this.listData = {
        deliveryTime: this.customerOrder.deliveryTime,
        buySeq: this.customerOrder.buySeq,
        deliveryType: this.customerOrder.deliveryType,
        needNote: this.customerOrder.needNote,
        buyerName: this.customerOrder.buyerName
      };
    },
    created() {
      this.pmId = getStore({name: "pmId"});
      this.getFetchList()
    },
    methods: {
      //获取店铺列表
      getFetchList() {
        let params = {
          current: 1,
          size: 100,
          merchantId: this.pmId,
          status: this.useStatus
        }
        fetchList(params).then(res => {
          // console.log(res.data.data.records);
          this.shopList = res.data.data.records
          this.shopId = this.shopList[0].shopId
        })
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
      },
      selectGoods(goods) {
        console.log(goods);
        this.dialogVisible = false
        let index = this.selectedRowIndex
        let orderItem = {
          goodsName: goods.goodsName + '(' + goods.modelName+')',
          // goodsModelList: goods.goodsModelList,
          // goodsList: [],
          goodsModelId: goods.modelId ,
          goodsNum: '',
          remarks: '',
          modelUrl: goods.modelUrl,
          purchasePrice: goods.modelPrice,
          modelUnit: goods.modelUnit
        }
        this.$set(this.orderList, index, orderItem)
        // this.onModelSelectChange(orderItem.goodsModelList[0].id, orderItem)
      },
      onSelectList(list) {
        this.$refs.excelBox.btnFlag = true;
        let params = {};
        params.list = list;
        importTable(params).then(res => {
          this.$notify({
            title: '提示',
            message: res.data.data,
            duration: 50000
          });
          this.is_excel = false;
        }).catch(err => {
          this.$notify({
            title: '提示',
            message: err,
            duration: 50000
          });
        }).finally(() => {
          if (this.$refs.excelBox) {
            this.$refs.excelBox.btnFlag = false;
          }
        })
      },
      //改变配送时间时
      changeTime(value) {
        this.listData.deliveryTime = value;
        this.orderList = this.orderListInfo();
      },
      changebuySeq(value) {
        this.listData.buySeq = value;
      },
      /**
       * 页面请求
       */
      getGoodsList(params) {
        params.size = 20;
        params.current = 1
        params.shopId = this.shopId;
        params.buyerId = this.customerOrder.buyerId;
        return getgoodslist(params).then(res => {
          console.log(res);
          if (res.data.code == 0) {
            return res.data.data.records
          } else {
            this.$message.warning('商品列表获取错误', res.msg)
          }
          return []
        })
      },
      fetchBuyerList(params={}) {
        params.current = 1
        params.size = 10
        console.log(params);
        getBuyerList(params).then(res => {
          if(res.data.code == 0) {
            this.buyerList = res.data.data.records
          }
        })
      },
      remoteTelephone(telephone = null) {
        let params = {
          telephone: telephone
        }
        this.fetchBuyerList(params)
      },
      remoteContact(contact = null) {
        let params = {
          contact: contact
        }
        this.fetchBuyerList(params)
      },
      remoteBuyerName(buyerName = null) {
        let params = {
          buyerName: buyerName
        }
        this.fetchBuyerList(params)
      },
      addBuyOrder(params = {}) {

        let data = {
          buyerId: params.buyerId,
          deliveryDate: params.deliveryTime,
          buySeq: params.buySeq,
          needNote: params.needNote,
          shipFee: params.shipFee,
          deliveryType: params.deliveryType,
          detailList: params.buyOrderDetailList
        }
        console.log(data);
        return addNewOder(data)
      },
      /**
       * 页面方法
       */
      onBuyerChange(value, type) {
        this.listData.buyerName = value;
        this.disabled = false;
        let index = this.buyerList.map(i => i[type]).indexOf(value)
        this.setCustomerForm(index)
        this.orderList = this.orderListInfo();
      },
      setCustomerForm(index) {
        let buyer = this.buyerList[index];
        this.$set(this.customerOrder, 'buyerUid', buyer.uid)
        this.$set(this.customerOrder, 'buyerId', buyer.id)
        this.$set(this.customerOrder, 'buyerName', buyer.buyerName)
        this.$set(this.customerOrder, 'contact', buyer.contact)
        this.$set(this.customerOrder, 'telephone', buyer.telephone)
        this.$set(this.customerOrder, 'address', buyer.address)
        this.listData.buyerId = buyer.id;
      },
      searchGoodsByName(row) {
        // 将row信息传入
        let _this = this;
        return function (searchValue) {
          if (searchValue !== '') {
            row.loading = true
            let params = {
              goodsName: searchValue,
              deliveryDate: _this.customerOrder.deliveryTime
            }
            _this.getGoodsList(params).then(res => {
              console.log('搜索',res)
              _this.$set(row, 'goodsList', res)
              _this.$set(row, 'loading', false)
            })
          }
        }
      },
      onGoodsSelectChange(e, row) {
        console.log(e,row)
        if (e) {
          let selectedGoods = row.goodsList.filter(item => item.modelId === e)[0]
          // row.goodsModelList = selectedGoods.goodsModelList
          console.log('select',selectedGoods);
          this.$set(row, 'goodsName', selectedGoods.goodsName+'（'+selectedGoods.modelName+')')
          this.$set(row, 'modelUrl', selectedGoods.modelUrl)
          this.$set(row, 'goodsModelId', selectedGoods.modelId)
          this.$set(row, 'purchasePrice', selectedGoods.modelPrice)
          this.$set(row, 'modelUnit', selectedGoods.modelUnit)
          // this.onModelSelectChange(selectedGoods.goodsModelList[0].id, row)
          row.goodsModel = ''
        } else {
          // 清空选项时
          this.$set(row, 'goodsId', '');
          row.goodsId = '';
        }
      },
      // onModelSelectChange(e, row) {
      //   let selectedModel = row.goodsModelList.filter(item => item.id === e)[0]
      //   this.$set(row, 'goodsId', selectedModel.id)
      //   this.$set(row, 'purchasePrice', selectedModel.purchasePrice || selectedModel.modelPrice)
      //   this.$set(row, 'goodsImg', selectedModel.modelUrl)
      //   this.$set(row, 'goodsModel', selectedModel.modelName)
      //   this.$set(row, 'unit', selectedModel.modelUnit)
      //   this.$set(row, 'buyPrice', selectedModel.buyPrice)
      // },
      showGoodsDialog($event, index) {
        this.dialogVisible = true
        this.selectedRowIndex = index
      },
      // onSelectGoods(goods) {
      //   this.dialogVisible = false
      //   let index = this.selectedRowIndex
      //   let orderItem = {
      //     goodsName: goods.goodsName,
      //     goodsModelList: goods.goodsModelList,
      //     goodsList: [],
      //     goodsNum: '',
      //     remarks: '',
      //     thumbUrl: goods.thumbUrl
      //   }
      //   this.$set(this.orderList, index, orderItem)
        // this.onModelSelectChange(orderItem.goodsModelList[0].id, orderItem)
      // },
      addOrderItem() {
        this.orderList.push(this.orderListInfo()[0]);
      },
      delOrderItem(e, index) {
        this.orderList.splice(index, 1)
      },
      resetForm() {
        this.disabled = true;
        this.customerOrder = this.customerOrderInfo();
      },
      submitBuyOrder() {
        let params = {
          buyerId: this.customerOrder.buyerId,
          // pmId: getStore({name: "pmId"})
        }
        queryStatus(params).then(res => {
          console.log(res);
          if (res.data.data != true) {
            this.$message.warning('当前采购商不可下单');
            return false;
          } else {
            this.createOrder();
          }
        })
      },
      createOrder() {
        this.$confirm("您现在已经完成了" + this.orderList.length + "个商品的录入,确认下单？").then(res => {
          let order = this.customerOrder
          let orderDetail = this.genOrderDetail()
          Object.assign(order, {
            ...orderDetail
          })
          for (var i in order.buyOrderDetailList) {
            if (order.buyOrderDetailList[i].goodsNum == '') {
              this.$message.warning('请输入数量');
              return false;
            }
          }
          if (!this.checkCustomerRule()) return;
          if (!this.checkOrderRule()) return;
          // this.addBuyOrder(order)
          console.log('params',order);
          this.addBuyOrder(order).then(res => {
            let msg = '订单号: ' + res.data.data.buyOrderSn
            this.$alert(msg, '提交成功', {
              confirmButtonText: '确定'
            })
            console.log(res);
            let info = this.customerOrderInfo();
            info.deliveryTime = order.deliveryDate;
            info.buySeq = order.buySeq;
            info.deliveryType = order.deliveryType;
            this.customerOrder = info;
            this.disabled = true;
            this.orderList = this.orderListInfo();
            this.orderTextVisible = false;
          })
        })
      },
      genOrderDetail() {
        let order = this.orderList
        let genPrice = 0
        console.log(order);
        let buyOrderDetailList = order.map((item, index) => {
          genPrice += (+item.goodsNum) * (+item.purchasePrice)
          return {
            goodsModelId: item.goodsModelId,
            goodsId: item.goodsId,
            goodsName: item.goodsName,
            goodsNum: item.goodsNum,
            purchasePrice: item.purchasePrice,
            buyPrice: item.buyPrice,
            unit: item.unit,
            remarks: item.remarks,
          }
        })

        return {
          buyOrderDetailList,
          genPrice: genPrice.toFixed(2)
        }
      },
      checkCustomerRule() {
        let result = false
        this.$refs["customerForm"].validate((valid) => {
          console.log(valid);
          if (valid) {
            result = valid;
          } else {
            this.$message.warning('客户信息校验错误!!');
          }
        });
        return result;
      },
      checkOrderRule() {
        let order = this.orderList
        let result = false
        order.forEach((item, index) => {
          this.$refs["orderDetail" + index].validate((valid) => {
            if (valid) {
              result = valid;
            } else {
              this.$message.warning('订单信息校验错误!!');
            }
          })
        })
        return result
      },
      /**
       * 表格样式
       */
      thStyle() {
        return {
          background: '#494949',
          fontSize: '18px',
          color: '#fff'
        }
      },
      tomorrow() {
        return this.$utils.getDiffDate(1);
      },
      customerOrderInfo() {
        return {
          buyerUid: '',
          buyerId: '',
          buyerName: '',
          contact: '',
          telephone: '',
          address: '',
          needNote: '',
          deliveryTime: this.tomorrow(),
          buySeq: '0',
          genPrice: 0,
          totalNum: 0,
          deliveryType: '9'
        };
      },
      orderListInfo() {
        return [{
          goodsModelId: '',
          goodsId: '',
          thumbUrl: '',
          goodsName: '',
          goodsModel: '',
          goodsNum: '',
          purchasePrice: '',
          buyPrice: '',
          unit: '',
          remarks: '',
          loading: false,
          goodsList: [],
          goodsModelList: [],
        }];
      },
      showTextArea() {
        // 已选择采购商时
        if (this.customerOrder.buyerId) {
          this.orderTextVisible = true;
        } else {
          this.$message.warning("请选择采购商");
        }
      },
      orderTextSubmit() {
        if (!this.orderText) {
          this.$message.warning("请填写订单内容");
          return '';
        }
        let regex = /[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}]+[0-9]+[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}]/ug;
        let goodsList = this.orderText.match(regex);
        console.info("goodsList", goodsList);
        if (!goodsList) {
          this.$message.warning("请填写订单内容");
          return '';
        }
        let regexName = /[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}]+/u;
        let regexNum = /[0-9]+/;
        // 新增商品加入采购列表
        let i = 0;
        goodsList.forEach(item => {
          let name = item.match(regexName);
          let num = item.match(regexNum);
          if (name && num) {
            name = name[0];
            num = num[0];
            let info = {
              goodsModelId: '',
              goodsId: '',
              goodsImg: '',
              goodsName: name,
              goodsNum: num,
              goodsModel: '',
              purchasePrice: '',
              buyPrice: '',
              unit: '',
              remarks: '',
              loading: false,
              goodsList: [],
              goodsModelList: [],
              sort: i
            }
            let params = {
              goodsName: name,
              shopId: this.shopId
            };
            this.getGoodsList(params).then(res => {
              if (res.length > 0) {
                info.goodsList = res;
              }
              this.orderList.push(info);
            });
            i++;
          }
        });
      },
      orderSort() {
        this.orderList.sort(function (a, b) {
          return a.sort - b.sort;
        });
      }
    }
  };

</script>

<style scoped lang="scss">
  .upload-demo {
    display: inline-block;
    margin-left: 10px;
  }

  .page-wrap {
    height: 100%;

    .title {
      padding: 10px;
    }
  }

  .buyer-info,
  .body {
    background: #fff;
  }

  .buyer-info {
    font-size: 16px;
  }

  .body {
    position: relative;
    /*height: calc(100vh - 600px);*/
    /*min-height: 600px;*/
    margin-top: 10px;
    overflow: auto;
    width: 100%;
  }

  .el-form-item {
    margin: 15px 5px;
  }

  .row {
    margin-bottom: 10px;
  }

  .form-field--small {
    width: 150px;
  }

  .form-field {
    width: 150px;
  }

  .form-field--large {
    width: 200px;
  }

</style>
